import React, { PureComponent } from 'react';
import { connect } from 'react-redux'
import PropTypes, { bool,string } from 'prop-types'
import styled from 'styled-components'
import { Switch ,Route,withRouter } from 'react-router-dom'
import { getNewsList } from '../../actions/newsListActionCreator'
import './index.css'

import {
	NewsTitle,
	Article
} from "./components"

const Loading  = styled.h2`
	color:red;
	font-size:20px;
`;

class NewList extends PureComponent {
	constructor(props) {
		super(props);
		this.state = {  }
		console.log("newList",props)
	}
	componentDidMount(){
		// this.props.getNewsList()
	}
	static propTypes = {
		list:PropTypes.arrayOf(PropTypes.shape({
			title:string,
			text:string
		})).isRequired,
		isLoading:bool,
		errMsg:PropTypes.string
	}
	static defaultProps = {
		list:[],
		isLoading:true,
		errMsg:"加载中"
	}
	render() { 
		const { isLoading,errMsg,list,match } = this.props;
		let article = {};
		let id = match.params.id;
		console.log(match);
		if(id){
			article = list.find(item=>{
				return item.key == id
			})
		}else{
			article = list[0]||{}
		}
		return ( <div className="newsBox">
			<ol  className="navBar">
				{
					this.props.list.map((item)=>{
						return <NewsTitle key={item.key} title={item.title} id={item.key} readCount={item.readCount} />
					})
				}
			</ol>
			<div className="article" >
				<Switch>
					<Route path="/news/:id"  render={
						(routeRprops)=>{
							console.log(routeRprops)
							let id = routeRprops.match.params.id;
							let article = {};
							if(id){
								article = list.find(item=>{
									return item.key == id
								})
							}else{
								article = list[0]||{}
							}
							return <Article item={article}/>
						}
					}/>
				</Switch>
			</div>
		</div> );
	}
}
const getStatefromProps = (state)=>{
	let newState = Object.assign({},state);
	return {
		list:newState.newsList.list,
		isLoading:newState.newsList.isLoading,
		errMsg:newState.newsList.errMsg
	}
}


export default withRouter(connect(getStatefromProps,{getNewsList})(NewList));